package com.pro01.apirednote.controller;

import com.pro01.apirednote.dto.UpdateUserRoleRequest;
import com.pro01.apirednote.dto.UserInfoAdminResponse;
import com.pro01.apirednote.pojo.PageResult;
import com.pro01.apirednote.pojo.Result;
import com.pro01.apirednote.pojo.User;
import com.pro01.apirednote.service.UserService;
import com.pro01.apirednote.mapper.UserMapper;
import com.pro01.apirednote.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/users")
@RequiredArgsConstructor
@Slf4j
public class AdminUserController {

    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;
    private final UserMapper userMapper;
    
    private static final String USER_CACHE_PREFIX = "user:";

    // 管理员查看所有用户信息
    @GetMapping
    public Result<PageResult<UserInfoAdminResponse>> getAllUsers(@RequestParam(defaultValue = "1") int pageNum,
                                                                 @RequestParam(defaultValue = "10") int pageSize,
                                                                 HttpServletRequest request) {
        String role = TokenUtil.getRole(request);
        if (!"ADMIN".equals(role)) {
            return Result.error("无权限访问");
        }

        PageResult<User> userPage = userService.getAllUsers(pageNum, pageSize);

        // 转换为脱敏 DTO
        List<UserInfoAdminResponse> dtoList = userPage.getRecords().stream().map(user -> {
            UserInfoAdminResponse dto = new UserInfoAdminResponse();
            dto.setId(user.getId());
            dto.setUsername(user.getUsername());
            dto.setRole(user.getRole());
            dto.setCreatedAt(user.getCreatedAt());

            Long uid = user.getId();

            // 加上 null 判断，避免返回值为 null
            Integer contentCount = userMapper.countContentsByUser(uid);
            Integer commentCount = userMapper.countCommentsByUser(uid);
            Integer totalViewCount = userMapper.countTotalViewsByUserId(uid);
            Integer receivedCommentCount = userMapper.countReceivedComments(uid);
            Integer receivedLikeCount = userMapper.sumReceivedLikes(uid);

            dto.setContentCount(contentCount != null ? contentCount : 0);
            dto.setCommentCount(commentCount != null ? commentCount : 0);
            dto.setTotalViewCount(totalViewCount != null ? totalViewCount : 0);
            dto.setReceivedCommentCount(receivedCommentCount != null ? receivedCommentCount : 0);
            dto.setReceivedLikeCount(receivedLikeCount != null ? receivedLikeCount : 0);

            return dto;
        }).toList();

        PageResult<UserInfoAdminResponse> result = new PageResult<>(userPage.getTotal(), dtoList);
        return Result.success(result);
    }

    // 管理员修改用户权限
    @PutMapping("/{userId}/role")
    public Result<?> updateUserRole(@PathVariable Long userId,
                                    @RequestBody UpdateUserRoleRequest request,
                                    HttpServletRequest httpRequest) {
        // 权限检查
        if (!"ADMIN".equals(TokenUtil.getRole(httpRequest))) {
            return Result.error("无权限操作");
        }

        // 参数校验
        String newRole = request.getRole();
        if (!"USER".equals(newRole) && !"ADMIN".equals(newRole)) {
            return Result.error("无效的角色类型");
        }

        boolean updated = userService.updateUserRole(userId, newRole);
        return updated ? Result.success() : Result.error("修改失败，用户不存在");
    }
    
    /**
     * 清除用户缓存
     * @param userId 用户ID，如果为null则清除所有用户缓存
     * @param httpRequest HTTP请求
     * @return 操作结果
     */
    @PostMapping("/cache/clear")
    public Result<String> clearUserCache(@RequestParam(required = false) Long userId, 
                                        HttpServletRequest httpRequest) {
        // 权限检查
        if (!"ADMIN".equals(TokenUtil.getRole(httpRequest))) {
            return Result.error("无权限操作");
        }
        
        try {
            if (userId != null) {
                // 清除特定用户的缓存
                String idKey = "user:id:" + userId;
                Object user = redisTemplate.opsForValue().get(idKey);
                if (user != null) {
                    // 如果是User对象或Map，尝试获取username以清除username缓存
                    String username = null;
                    if (user instanceof User) {
                        username = ((User) user).getUsername();
                    } else if (user instanceof java.util.Map) {
                        username = (String) ((java.util.Map) user).get("username");
                    }
                    
                    // 删除用户ID缓存
                    redisTemplate.delete(idKey);
                    
                    // 删除用户名缓存
                    if (username != null) {
                        redisTemplate.delete("user:name:" + username);
                    }
                    
                    log.info("已清除用户缓存，userId: {}", userId);
                    return Result.success("已清除指定用户的缓存");
                } else {
                    return Result.success("未找到指定用户的缓存");
                }
            } else {
                // 清除所有用户缓存
                Set<String> keys = redisTemplate.keys(USER_CACHE_PREFIX + "*");
                if (keys != null && !keys.isEmpty()) {
                    redisTemplate.delete(keys);
                    log.info("已清除所有用户缓存，共{}条", keys.size());
                    return Result.success("已清除所有用户缓存，共" + keys.size() + "条");
                } else {
                    return Result.success("未找到用户缓存");
                }
            }
        } catch (Exception e) {
            log.error("清除用户缓存失败", e);
            return Result.error("清除缓存失败: " + e.getMessage());
        }
    }
}